#! /usr/bin/python
# -*- coding:  utf-8 -*-
#
# accoufer : cgi script for creating new user account
# 
# Copyright S.Keim 2011
# Available under the MIT licence see the COPYING file


import accoufer
import shelve
import cgi 

def run():
    # extract parameters
    form = cgi.FieldStorage()
    if "login" not in form:
        print accoufer.HTML%("Create new user", FORM)
        return 
    try:
        login = form["login"].value
        email = form["email"].value
        pwd1 = form["pwd1"].value
        pwd2 = form["pwd2"].value
    except KeyError:
        return error("Invalid parameters")

    if pwd1!=pwd2:
       return error("Password mismatch")

    #create new user
    users = shelve.open(accoufer.USER_PATH)
    if login in users:
       return error("Login already used")
       
    # TODO check user letters only (not'.', ' '...)
    
    emails = shelve.open(accoufer.EMAIL_PATH)
    if email in emails:
       return error("Email already used")
    user = (email, accoufer.md5(pwd1).digest(),  50, []) # we create new user accounts with 50 credits
    users[login] = user
    emails[email] = login

    # output message
    header = accoufer.cookieHeader(login)
    msg =  SUCCES%login
    print accoufer.HTML_HEADER%(header, "User created", msg )


def error(txt):
    
    msg = ERROR%txt
    print accoufer.HTML%("Error", msg)


SUCCES = """<h1>New user</h1>User "%s" successfully created with 50 credits.<p/> <hr/> <a href="./index.html">Start</a>"""

INFORM = """<form method=post action="./xnewuser">
Login: <input name="login" /><br/>
Password: <input type="password" name="pwd1" /><br/>
Repeat password: <input type="password" name="pwd2" /><br/>
Email: <input name="email" /><br/>
<input type="submit" value="Run"/></form>"""

ERROR = "<h1>New user</h1><b>%s</b><p/>"+INFORM

FORM = "<h1>New user</h1>"+INFORM

if __name__=="__main__":
    run()

